package com.mrd.gtimp.base.action;

import com.mrd.constant.MsgConstants;
import com.mrd.constant.StateConstats;
import com.mrd.constant.WebPathConstants;
import com.mrd.exception.QueryException;
import com.mrd.framework.config.web.json.Result;
import com.mrd.framework.config.web.json.annotation.JField;
import com.mrd.framework.config.web.json.annotation.Json;
import com.mrd.framework.ui.Jqgrid;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.gtimp.base.entity.Dept;
import com.mrd.gtimp.base.entity.Module;
import com.mrd.gtimp.base.entity.Permissions;
import com.mrd.gtimp.base.entity.Role;
import com.mrd.gtimp.base.entity.User;
import com.mrd.gtimp.base.service.RoleBiz;
import com.mrd.gtimp.base.service.UserBiz;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;


/**
 * <p> application name: gtimp <p> copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author qiul
 */

@Controller
@RequestMapping("/base")
public class RoleAction {
    private static final long serialVersionUID = 1L;

    @Resource
    private RoleBiz roleBiz;
    /**
     * 根据该值进行判断点击事件是触发权限设置页面还是触发可管理权限页面 0为权限设置页面，1为可管理权限页面
     */
    private String type;

    @Resource
    private UserBiz userBiz;


    /**
     * 角色权限管理入口
     */
    @RequestMapping("/role-main")
    public String main(Model model) {
//        left = "role-setlist.do";
//        right = "";
//        title = "角色权限管理";
        model.addAttribute("title", "角色权限管理");
        model.addAttribute("left", "role-setlist");
        model.addAttribute("right", "");
        return WebPathConstants.FRAME_WEB_PATH;
    }

    /**
     * 角色可管理权限入口
     */
    @RequestMapping("/role-managemain")
    public String managemain(Model model) {
//        left = "role-managelist.do";
//        right = "";
//        title = "角色可管理权限管理";
        model.addAttribute("title", "角色可管理权限管理");
        model.addAttribute("left", "role-managelist");
        model.addAttribute("right", "");
        return WebPathConstants.FRAME_WEB_PATH;
    }

    /**
     * 用户权限管理
     */
    @RequestMapping("/role-roleuser")
    public String roleuser(Model model) {
//        left = "role-list.do";
//        right = "";
//        title = "权限管理";
        model.addAttribute("title", "权限管理");
        model.addAttribute("left", "role-list");
        model.addAttribute("right", "");
        return WebPathConstants.FRAME_WEB_PATH;
    }

    /**
     * 获取角色用户
     */
    @RequestMapping("/role-user")
    public String user(String id, Model model) {
        model.addAttribute("id", id);
        return "/gtimp/base/role/role/roleuser/role-user";
    }

    /**
     * 角色管理入口
     */
    @RequestMapping("/role-list")
    public String list() {
        return "/gtimp/base/role/role/roleuser/role-list";
    }

    /**
     * 权限设置角色列表入口
     */
    @RequestMapping("/role-setlist")
    public String setlist() {
        return "/gtimp/base/role/role/rolemodule/role-list";
    }

    /**
     * 可管理权限角色列表入口
     */
    @RequestMapping("/role-managelist")
    public String managelist() {
        return "/gtimp/base/role/role/rolemmodule/role-list";
    }

    /**
     * 添加跳转
     */
    @RequestMapping("/role-add")
    public String add() {
        return "/gtimp/base/role/role/roleuser/role-save";
    }

    /**
     * 修改跳转
     */
    @RequestMapping("/role-update")
    public String update(String id, Model model) {
        if (StringUtils.isNotEmpty(id)) {
            model.addAttribute("id", id);
        }
        return "/gtimp/base/role/role/roleuser/role-save";
    }

    /**
     * 获取待修改数据
     */
    @RequestMapping("/role-beUpdate")
    @ResponseBody
    @Json({@JField("id"), @JField("name"), @JField("company"), @JField("state")})
    public Role beUpdate(String id) {
        try {
            if (StringUtils.isNotEmpty(id)) {
                try {
                    Role role = roleBiz.findEntityById(id);
                    return role;
                } catch (QueryException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除角色
     */
    @RequestMapping("/role-del")
    @ResponseBody
    public Result del(String id) {
        Result msg;
        try {
            if (StringUtils.isNotEmpty(id)) {
                Role role = roleBiz.findEntityById(id);
                //roleBiz.delete(role, true);
            }
            msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
        } catch (Exception e) {
            e.printStackTrace();
            msg = Result.newFailInstance(MsgConstants.SAVE_FAIL);
        }
        return msg;
    }

    /**
     * 保存
     */
    @RequestMapping("/role-save")
    @ResponseBody
    public Result save(Role role) {
        Result msg;
        try {
            if (StringUtils.isEmpty(role.getId())) {
                role.setId(null);
            }
            roleBiz.saveOrupdateEntity(role);
            msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
        } catch (Exception e) {
            e.printStackTrace();
            msg = Result.newFailInstance(MsgConstants.SAVE_FAIL);
        }
        return msg;
    }

    /**
     * 获取角色列表
     */
    @RequestMapping("/role-data")
    @ResponseBody
    @Json({@JField("id"), @JField("name")})
    public List<Role> data(Filter filters) {
        try {
            filters.addRule(new SearchRule("state", SearchRuleOption.eq, StateConstats.USE_STATE[0][1]));
            List<Role> roles = roleBiz.findEntityByFilter(0, 0, filters, new Sort.Order("name"));
            if (!roles.isEmpty()) {
                return roles;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 模块权限入口
     */
    @RequestMapping("/role-module")
    public String module(String id, Model model) {
        model.addAttribute("id", id);
        return "/gtimp/base/role/role/rolemodule/role-module";
    }

    /**
     * 角色权限入口
     */
    @RequestMapping("/role-permissions")
    public String permissions(String rid, String mid, Model model) {
        model.addAttribute("rid", rid);
        model.addAttribute("mid", mid);
        return "/gtimp/base/role/role/rolemodule/role-permissions";
    }

    /**
     * 可管理模块入口
     */
    @RequestMapping("/role-mmodule")
    public String mmodule(String id, Model model) {
        model.addAttribute("id", id);
        return "/gtimp/base/role/role/rolemmodule/role-m-module";
    }

    /**
     * 可管理角色权限入口
     */
    @RequestMapping("/role-mpermissions")
    public String mpermissions(String rid, String mid, Model model) {
        model.addAttribute("rid", rid);
        model.addAttribute("mid", mid);
        return "/gtimp/base/role/role/rolemmodule/role-m-permissions";
    }

    /**
     * 获取当前角色的模块权限列表
     */
    @RequestMapping("/role-moduledata")
    @ResponseBody
    public Map<String, Object> moduledata(String rid, String mid) {
        try {
            Map<String, Object> result = new HashMap<>();
            if (StringUtils.isNotEmpty(rid)) {
                Role role = roleBiz.findEntityById(rid);
                List<Module> modules = roleBiz.findRoleModule(rid, mid);
                role.setModules(modules);

                List<Map<String, Object>> tempList = new ArrayList<>();
                for (Module m : modules) {
                    Map<String, Object> tempMap = new HashMap<>();
                    tempMap.put("checked", m.getChecked());
                    tempMap.put("id", m.getId());
                    tempMap.put("isParent", m.getIsParent());
                    tempMap.put("link", m.getLink());
                    tempMap.put("name", m.getName());
                    tempMap.put("order", m.getOrder());
                    tempMap.put("parent", m.getParent());
                    tempMap.put("state", m.getState());
                    tempList.add(tempMap);
                }
                result.put("id", role.getId());
                result.put("modules", tempList);
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当前角色的可管理模块权限列表
     */
    @RequestMapping("/role-mmoduledata")
    @ResponseBody
    public Map<String, Object> mmoduledata(String rid, String mid) {
        try {
            Map<String, Object> result = new HashMap<>();
            if (StringUtils.isNotEmpty(rid)) {
                Role role = roleBiz.findEntityById(rid);
                List<Module> modules = roleBiz.findRoleManageModule(role.getId(), mid);
                role.setModules(modules);

                List<Map<String, Object>> tempList = new ArrayList<>();
                for (Module m : modules) {
                    Map<String, Object> tempMap = new HashMap<>();
                    tempMap.put("checked", m.getChecked());
                    tempMap.put("id", m.getId());
                    tempMap.put("isParent", m.getIsParent());
                    tempMap.put("link", m.getLink());
                    tempMap.put("name", m.getName());
                    tempMap.put("order", m.getOrder());
                    tempMap.put("parent", m.getParent());
                    tempMap.put("state", m.getState());
                    tempList.add(tempMap);
                }
                result.put("id", role.getId());
                result.put("modules", tempList);
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 保存角色模块权限
     */
    @RequestMapping("/role-saveRoleModule")
    @ResponseBody
    public Result saveRoleModule(Role role) {
        Result msg;
        try {
            roleBiz.saveRoleModule(role);
            msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
        } catch (Exception e) {
            e.printStackTrace();
            msg = Result.newFailInstance(MsgConstants.SAVE_FAIL);
        }
        return msg;
    }

    /**
     * 保存角色可管理模块权限
     */
    @RequestMapping("/role-saveRoleMModule")
    @ResponseBody
    public Result saveRoleMModule(Role role) {
        Result msg;
        try {
            roleBiz.saveRoleManageModule(role);
            msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
        } catch (Exception e) {
            e.printStackTrace();
            msg = Result.newFailInstance(MsgConstants.SAVE_FAIL);
        }
        return msg;
    }

    /**
     * 获取当前选择的模块的权限数据
     */
    @RequestMapping("/role-perdata")
    @ResponseBody
    public Map<String, Object> perdata(String rid, String mid) {
        try {
            List<Permissions> permissions = null;
            Map<String, Object> result = null;
            if (StringUtils.isNotEmpty(rid) && StringUtils.isNotEmpty(mid)) {
                permissions = roleBiz.findRoleModulePermissions(rid, mid);
                Role role = roleBiz.findEntityById(rid);
                role.setPermissions(permissions);

                result = new HashMap<>();
                Map<String, Object> roleMap = new HashMap<>();
                roleMap.put("id", role.getId());
                if (permissions != null && !permissions.isEmpty()) {
                    List<Map<String, Object>> permissionsList = new ArrayList<>();
                    for (Permissions permission : permissions) {
                        Map<String, Object> permissionMap = new HashMap<>();
                        permissionMap.put("buttonId", permission.getButtonId());
                        permissionMap.put("checked", permission.getChecked());
                        permissionMap.put("click", permission.getClick());
                        permissionMap.put("disable", permission.getDisable());
                        permissionMap.put("hidden", permission.getHidden());
                        permissionMap.put("id", permission.getId());
                        permissionMap.put("label", permission.getLabel());
                        permissionMap.put("module", permission.getModule());
                        permissionMap.put("name", permission.getName());
                        permissionMap.put("pid", permission.getPid());
                        permissionMap.put("type", permission.getType());
                        permissionsList.add(permissionMap);
                    }
                    roleMap.put("permissions", permissionsList);
                }
                result.put("role", roleMap);
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当前选择的模块的权限数据
     */
    @RequestMapping("/role-mperdata")
    @ResponseBody
    public Map<String, Object> mperdata(String rid, String mid) {
        try {
            List<Permissions> permissions = null;
            Map<String, Object> result = null;
            if (StringUtils.isNotEmpty(rid) && StringUtils.isNotEmpty(mid)) {
                permissions = roleBiz.findRoleManageModulePermissions(rid, mid);
                Role role = roleBiz.findEntityById(rid);
                role.setPermissions(permissions);

                result = new HashMap<>();
                Map<String, Object> roleMap = new HashMap<>();
                roleMap.put("id", role.getId());
                if (permissions != null && !permissions.isEmpty()) {
                    List<Map<String, Object>> permissionsList = new ArrayList<>();
                    for (Permissions permission : permissions) {
                        Map<String, Object> permissionMap = new HashMap<>();
                        permissionMap.put("buttonId", permission.getButtonId());
                        permissionMap.put("checked", permission.getChecked());
                        permissionMap.put("click", permission.getClick());
                        permissionMap.put("disable", permission.getDisable());
                        permissionMap.put("hidden", permission.getHidden());
                        permissionMap.put("id", permission.getId());
                        permissionMap.put("label", permission.getLabel());
                        permissionMap.put("module", permission.getModule());
                        permissionMap.put("name", permission.getName());
                        permissionMap.put("pid", permission.getPid());
                        permissionMap.put("type", permission.getType());
                        permissionsList.add(permissionMap);
                    }
                    roleMap.put("permissions", permissionsList);
                }
                result.put("role", roleMap);
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 保存角色可管理权限
     */
    @RequestMapping("/role-saveRoleManagePer")
    @ResponseBody
    public Result saveRoleManagePer(Role role) {
        Result msg;
        try {
            roleBiz.saveRoleManagePermissions(role);
            msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.SAVE_FAIL);
            e.printStackTrace();
        }
        return msg;
    }

    /**
     * 保存角色权限
     */
    @RequestMapping("/role-saveRolePer")
    @ResponseBody
    public Result saveRolePer(Role role) {
        Result msg;
        try {
            roleBiz.saveRolePermissions(role);
            msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.SAVE_FAIL);
            e.printStackTrace();
        }
        return msg;
    }

    /**
     * 列出部门下的角色用户
     */
    @RequestMapping("/role-listRoleUser")
    @ResponseBody
    public Page<User> listRoleUser(Jqgrid jqgrid, User user, Dept dept, Role role) {
        try {
            if (StringUtils.isNotEmpty(dept.getId())) {
                String deptId = dept.getId();
//                if (filters == null) {
//                    filters = new Filter();
//                    filters.setGroupOp(FilterGroupOption.AND);
//                }
                SearchRule sr = new SearchRule("depts.id", SearchRuleOption.eq, deptId);
                jqgrid.addRule(sr);

                Jqgrid jqgrid2 = new Jqgrid();
//                jqgrid2.setGroupOp(FilterGroupOption.AND);
                jqgrid2.addRule(new SearchRule("users.depts.id", SearchRuleOption.eq, deptId));
                jqgrid2.addRule(new SearchRule("id", SearchRuleOption.eq, role.getId()));
//                List<Role> r = roleBiz.findByJqgrid(0, 10, filter2, null);
                Page<Role> r = roleBiz.findByJqgrid(jqgrid);
                List<User> roleUsers = r.getContent().get(0).getUsers();
//                users = userBiz.findByJqgrid(0, 10, filters, null);
                Page<User> users = userBiz.findByJqgrid(jqgrid2);
                for (User u : users) {
                    for (User uu : roleUsers) {
                        if (u.getId().equals(uu.getId())) {
                            u.setChecked(true);
                        }
                    }
                }
                return users;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/role-saveRoleUser")
    @ResponseBody
    public Result saveRoleUser(String id) {
        Result msg;
        System.out.println("..");
        try {
            Role role = roleBiz.findEntityById(id);
            roleBiz.saveRoleUsers(role);
            msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.SAVE_FAIL);
            e.printStackTrace();
        }
        return msg;
    }

    @Resource
    public void setRoleBiz(RoleBiz roleBiz) {
        this.roleBiz = roleBiz;
    }

}
